import React, { useState, useEffect } from 'react';
import { get, post, put } from '../utils/api';
import { useAuth } from '../contexts/AuthContext';
import './Inventory.css';

interface InventoryItem {
  id: string;
  assetId: string;
  assetName: string;
  quantity: number;
  location: string;
  lastChecked: string;
  status: 'normal' | 'low' | 'out_of_stock';
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

interface InventoryFormData {
  assetId: string;
  quantity: number;
  location: string;
  notes: string;
}

const Inventory: React.FC = () => {
  const { user } = useAuth();
  const [inventory, setInventory] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingItem, setEditingItem] = useState<InventoryItem | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');

  const [formData, setFormData] = useState<InventoryFormData>({
    assetId: '',
    quantity: 0,
    location: '',
    notes: ''
  });

  const [assets, setAssets] = useState<Array<{id: string; name: string}>>([]);

  useEffect(() => {
    fetchInventory();
    fetchAssets();
  }, []);

  const fetchInventory = async () => {
    try {
      setLoading(true);
      const response = await get('/inventory');
      if (response.success) {
        setInventory(response.data);
      } else {
        setError('获取库存数据失败');
      }
    } catch (error) {
      console.error('Failed to fetch inventory:', error);
      setError('获取库存数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchAssets = async () => {
    try {
      const response = await get('/assets');
      if (response.success) {
        // 后端返回的数据结构是 { success: true, data: { assets: [...], pagination: {...} } }
        const assets = response.data.assets || [];
        setAssets(assets.map((asset: any) => ({
          id: asset.id,
          name: asset.name
        })));
      }
    } catch (error) {
      console.error('Failed to fetch assets:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      if (editingItem) {
        const response = await put(`/inventory/${editingItem.id}`, formData);
        if (response.success) {
          await fetchInventory();
          resetForm();
          setShowModal(false);
        } else {
          setError(response.message || '更新库存失败');
        }
      } else {
        const response = await post('/inventory', formData);
        if (response.success) {
          await fetchInventory();
          resetForm();
          setShowModal(false);
        } else {
          setError(response.message || '添加库存失败');
        }
      }
    } catch (error) {
      setError('操作失败，请稍后重试');
    }
  };

  const handleEdit = (item: InventoryItem) => {
    setEditingItem(item);
    setFormData({
      assetId: item.assetId,
      quantity: item.quantity,
      location: item.location,
      notes: item.notes || ''
    });
    setShowModal(true);
  };

  const handleStockCheck = async (id: string) => {
    try {
      const response = await post(`/inventory/${id}/check`, {});
      if (response.success) {
        await fetchInventory();
      } else {
        setError(response.message || '盘点失败');
      }
    } catch (error) {
      setError('盘点失败，请稍后重试');
    }
  };

  const resetForm = () => {
    setFormData({
      assetId: '',
      quantity: 0,
      location: '',
      notes: ''
    });
    setEditingItem(null);
    setError('');
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'quantity' ? parseInt(value) || 0 : value
    }));
  };

  // 过滤库存
  const filteredInventory = inventory.filter(item => {
    const matchesSearch = item.assetName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         item.location.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
    
    return matchesSearch && matchesStatus;
  });

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'normal':
        return '正常';
      case 'low':
        return '库存不足';
      case 'out_of_stock':
        return '缺货';
      default:
        return status;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'normal':
        return 'success';
      case 'low':
        return 'warning';
      case 'out_of_stock':
        return 'danger';
      default:
        return 'secondary';
    }
  };

  const getQuantityColor = (quantity: number, status: string) => {
    if (status === 'out_of_stock') return 'danger';
    if (status === 'low') return 'warning';
    return 'normal';
  };

  if (loading) {
    return (
      <div className="inventory-loading">
        <div className="spinner"></div>
        <p>加载库存数据...</p>
      </div>
    );
  }

  return (
    <div className="inventory">
      <div className="inventory-header">
        <h1>库存管理</h1>
        <button 
          onClick={() => setShowModal(true)} 
          className="btn btn-primary"
        >
          <span className="btn-icon">📦</span>
          添加库存
        </button>
      </div>

      {error && (
        <div className="alert alert-error">
          {error}
          <button onClick={() => setError('')} className="alert-close">×</button>
        </div>
      )}

      {/* 搜索和过滤 */}
      <div className="inventory-controls">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索资产名称或位置..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />
        </div>
        
        <div className="filter-box">
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="filter-select"
          >
            <option value="all">所有状态</option>
            <option value="normal">正常</option>
            <option value="low">库存不足</option>
            <option value="out_of_stock">缺货</option>
          </select>
        </div>
      </div>

      {/* 统计信息 */}
      <div className="inventory-stats">
        <div className="stat-item">
          <div className="stat-label">总库存项目</div>
          <div className="stat-value">{inventory.length}</div>
        </div>
        <div className="stat-item warning">
          <div className="stat-label">库存不足</div>
          <div className="stat-value">{inventory.filter(item => item.status === 'low').length}</div>
        </div>
        <div className="stat-item danger">
          <div className="stat-label">缺货</div>
          <div className="stat-value">{inventory.filter(item => item.status === 'out_of_stock').length}</div>
        </div>
      </div>

      {/* 库存列表 */}
      <div className="inventory-list">
        {filteredInventory.length > 0 ? (
          <div className="inventory-table">
            <table>
              <thead>
                <tr>
                  <th>资产名称</th>
                  <th>数量</th>
                  <th>位置</th>
                  <th>状态</th>
                  <th>最后盘点</th>
                  <th>备注</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {filteredInventory.map((item) => (
                  <tr key={item.id}>
                    <td className="asset-name">{item.assetName}</td>
                    <td className={`quantity ${getQuantityColor(item.quantity, item.status)}`}>
                      {item.quantity}
                    </td>
                    <td className="location">{item.location}</td>
                    <td>
                      <span className={`status-badge ${getStatusColor(item.status)}`}>
                        {getStatusText(item.status)}
                      </span>
                    </td>
                    <td className="date">{formatDate(item.lastChecked)}</td>
                    <td className="notes">{item.notes || '-'}</td>
                    <td className="actions">
                      <button
                        onClick={() => handleEdit(item)}
                        className="btn btn-sm btn-secondary"
                        title="编辑"
                      >
                        ✏️
                      </button>
                      <button
                        onClick={() => handleStockCheck(item.id)}
                        className="btn btn-sm btn-primary"
                        title="盘点"
                      >
                        📋
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="empty-state">
            <div className="empty-icon">📦</div>
            <h3>
              {searchTerm || filterStatus !== 'all' ? '没有找到匹配的库存' : '暂无库存数据'}
            </h3>
            <p>
              {searchTerm || filterStatus !== 'all' 
                ? '请尝试调整搜索条件或过滤器' 
                : '开始添加您的第一个库存项目'
              }
            </p>
            {(!searchTerm && filterStatus === 'all') && (
              <button 
                onClick={() => setShowModal(true)} 
                className="btn btn-primary"
              >
                添加库存
              </button>
            )}
          </div>
        )}
      </div>

      {/* 添加/编辑模态框 */}
      {showModal && (
        <div className="modal-overlay" onClick={() => {
          setShowModal(false);
          resetForm();
        }}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>{editingItem ? '编辑库存' : '添加库存'}</h2>
              <button 
                onClick={() => {
                  setShowModal(false);
                  resetForm();
                }}
                className="modal-close"
              >
                ×
              </button>
            </div>

            <form onSubmit={handleSubmit} className="modal-form">
              <div className="form-group">
                <label className="form-label">
                  选择资产 <span className="required">*</span>
                </label>
                <select
                  name="assetId"
                  value={formData.assetId}
                  onChange={handleChange}
                  className="form-select"
                  required
                  disabled={!!editingItem}
                >
                  <option value={0}>请选择资产</option>
                  {assets.map((asset) => (
                    <option key={asset.id} value={asset.id}>
                      {asset.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label className="form-label">
                    数量 <span className="required">*</span>
                  </label>
                  <input
                    type="number"
                    name="quantity"
                    value={formData.quantity}
                    onChange={handleChange}
                    className="form-input"
                    min="0"
                    required
                  />
                </div>

                <div className="form-group">
                  <label className="form-label">
                    位置 <span className="required">*</span>
                  </label>
                  <input
                    type="text"
                    name="location"
                    value={formData.location}
                    onChange={handleChange}
                    className="form-input"
                    required
                    placeholder="存放位置"
                  />
                </div>
              </div>

              <div className="form-group">
                <label className="form-label">备注</label>
                <textarea
                  name="notes"
                  value={formData.notes}
                  onChange={handleChange}
                  className="form-textarea"
                  rows={3}
                  placeholder="库存备注信息"
                />
              </div>

              <div className="modal-actions">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="btn btn-secondary"
                >
                  取消
                </button>
                <button type="submit" className="btn btn-primary">
                  {editingItem ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Inventory;
